package wedaex.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;

import wedaex.content.Page;
import wedaex.content.SimpleGetContentSource;
import wedaex.helper.HtmlProcessor;
import wedaex.helper.SessionUtils;

public class ProxyController implements Controller {
	protected Log log = LogFactory.getLog(ProxyController.class);
	
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String url = request.getParameter("url");
		if(StringUtils.isBlank(url))
			return new ModelAndView(new RedirectView("index.wdx"));

		// get the page
		SimpleGetContentSource source = SimpleGetContentSource.create(url);
		Page page = source.retrieveContent();
		if(log.isInfoEnabled()) log.info("Retrieved: " + page);

		// use the original encoding to display
		response.setCharacterEncoding(page.getEncoding());

		// add javascript to add controls to the page
		// getResponseBodyAsString() will automatically use request header's Content-Type to determine encoding
		String content = HtmlProcessor.addJavascript(page.getContent());
		
		// save page in session
		SessionUtils.setPage(page, request);
		
		content = HtmlProcessor.addProxyInfo(content, url);
		IOUtils.write(content, response.getOutputStream(), page.getEncoding());
		response.getOutputStream().close();

		return null;
	}

}
